const { app, BrowserWindow, ipcMain, dialog } = require('electron')
const path = require('path')
const fs = require('fs')
const os = require('os')
const { execSync } = require('child_process')
const isDev = process.env.NODE_ENV === 'development'
const sharp = require('sharp')

// 证件照尺寸配置(像素)
const PHOTO_SIZES = {
  '1inch': { width: 295, height: 413, label: '一寸(25×35mm)' },
  '2inch': { width: 413, height: 579, label: '二寸(35×49mm)' },
  'small1inch': { width: 260, height: 378, label: '小一寸(22×32mm)' },
  'large1inch': { width: 390, height: 567, label: '大一寸(33×48mm)' },
  'passport': { width: 390, height: 567, label: '护照(33×48mm)' },
  'visa': { width: 390, height: 567, label: '签证(33×48mm)' }
}

// 初始化性能历史数据
const performanceHistory = {
  cpu: [],
  memory: [],
  network: []
}

// 获取CPU使用率
async function getCpuUsage() {
  return new Promise((resolve) => {
    const startMeasure = os.cpus().map(cpu => cpu.times)
    setTimeout(() => {
      const endMeasure = os.cpus().map(cpu => cpu.times)
      const cpuUsage = endMeasure.map((end, i) => {
        const start = startMeasure[i]
        const idleDiff = end.idle - start.idle
        const totalDiff = Object.values(end).reduce((a, b) => a + b) - 
                         Object.values(start).reduce((a, b) => a + b)
        return {
          core: i,
          usage: (100 * (1 - idleDiff / totalDiff)).toFixed(1)
        }
      })
      
      const average = (cpuUsage.reduce((sum, cpu) => sum + parseFloat(cpu.usage), 0) / cpuUsage.length).toFixed(1)
      resolve({
        average,
        cores: cpuUsage
      })
    }, 100)
  })
}

// 获取网络流量
let lastNetworkStats = null
function getNetworkTraffic() {
  try {
    const networkInterfaces = os.networkInterfaces()
    const mainInterface = Object.values(networkInterfaces)
      .flat()
      .find(ni => !ni.internal && ni.family === 'IPv4')
    
    if (!mainInterface) return null

    const stats = {
      timestamp: Date.now(),
      rx: 0,
      tx: 0
    }
    
    // 在Windows上使用netstat命令获取网络统计信息
    const output = execSync('netstat -e', { encoding: 'utf8' })
    const lines = output.split('\n')
    if (lines.length >= 4) {
      const values = lines[3].trim().split(/\s+/)
      stats.rx = parseInt(values[1])
      stats.tx = parseInt(values[2])
    }
    
    if (lastNetworkStats) {
      const timeDiff = (stats.timestamp - lastNetworkStats.timestamp) / 1000 // 转换为秒
      const rxDiff = stats.rx - lastNetworkStats.rx
      const txDiff = stats.tx - lastNetworkStats.tx
      
      return {
        rxSpeed: formatBytes(rxDiff / timeDiff) + '/s',
        txSpeed: formatBytes(txDiff / timeDiff) + '/s',
        interface: mainInterface.address
      }
    }
    
    lastNetworkStats = stats
    return null
  } catch (error) {
    console.error('Error getting network traffic:', error)
    return null
  }
}

// 获取GPU信息
async function getGPUInfo() {
  try {
    const output = execSync('wmic path win32_VideoController get name,driverversion,videoprocessor,adapterram', { encoding: 'utf8' })
    const lines = output.split('\n').slice(1)
    const gpuInfo = lines
      .filter(line => line.trim())
      .map(line => {
        const [name, driverVersion, processor, ram] = line.trim().split(/\s{2,}/)
        return {
          name,
          driverVersion,
          processor,
          memory: formatBytes(parseInt(ram || 0))
        }
      })
    return gpuInfo
  } catch (error) {
    console.error('Error getting GPU info:', error)
    return null
  }
}

// 获取CPU温度
async function getCPUTemperature() {
  // 由于 Windows 系统权限限制，暂时禁用 CPU 温度检测
  return null;
}

// 获取系统启动时间
async function getBootTime() {
  try {
    const output = execSync('wmic os get lastbootuptime', { encoding: 'utf8' })
    const bootTime = output.split('\n')[1].trim()
    // 转换WMI时间格式为Date对象
    const year = bootTime.substring(0, 4)
    const month = bootTime.substring(4, 6)
    const day = bootTime.substring(6, 8)
    const hour = bootTime.substring(8, 10)
    const minute = bootTime.substring(10, 12)
    const second = bootTime.substring(12, 14)
    return new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`)
  } catch (error) {
    console.error('Error getting boot time:', error)
    return null
  }
}

// 格式化字节数
function formatBytes(bytes) {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化运行时间
function formatUptime(seconds) {
  const days = Math.floor(seconds / (24 * 60 * 60))
  const hours = Math.floor((seconds % (24 * 60 * 60)) / (60 * 60))
  const minutes = Math.floor((seconds % (60 * 60)) / 60)
  const parts = []
  if (days > 0) parts.push(`${days}天`)
  if (hours > 0) parts.push(`${hours}小时`)
  if (minutes > 0) parts.push(`${minutes}分钟`)
  return parts.join(' ')
}

// 创建主窗口
function createWindow() {
  const win = new BrowserWindow({
    width: 1280,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // 加载应用
  if (process.env.NODE_ENV === 'development') {
    win.loadURL('http://localhost:3000')
  } else {
    win.loadFile(path.join(__dirname, '../dist/index.html'))
  }

  return win
}

let mainWindow = null

// 加载设置
function loadSettings() {
  try {
    const settingsPath = path.join(app.getPath('userData'), 'settings.json');
    console.log('Settings path:', settingsPath); // 添加日志
    
    let settings;
    if (!fs.existsSync(settingsPath)) {
      settings = {
        refreshInterval: 2000,
        darkMode: false,
        cpuThreshold: 80,
        memoryThreshold: 80,
        diskThreshold: 90
      };
      // 确保目录存在
      fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
      fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
      console.log('Created default settings'); // 添加日志
    } else {
      const data = fs.readFileSync(settingsPath, 'utf8');
      settings = JSON.parse(data);
      console.log('Loaded existing settings'); // 添加日志
    }
    return settings;
  } catch (error) {
    console.error('加载设置失败:', error);
    // 返回默认设置而不是 null
    return {
      refreshInterval: 2000,
      darkMode: false,
      cpuThreshold: 80,
      memoryThreshold: 80,
      diskThreshold: 90
    };
  }
}

// 保存设置
function saveSettings(settings) {
  try {
    const settingsPath = path.join(app.getPath('userData'), 'settings.json');
    // 确保目录存在
    fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
    fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
    
    // 广播设置更新
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send('settings-updated', settings);
    }
    console.log('Settings saved successfully'); // 添加日志
    return true;
  } catch (error) {
    console.error('保存设置失败:', error);
    return false;
  }
}

// 在 app.whenReady() 之前注册所有 IPC 处理程序
ipcMain.handle('save-settings', async (event, settings) => {
  console.log('Saving settings:', settings); // 添加日志
  return saveSettings(settings);
});

ipcMain.handle('load-settings', async () => {
  console.log('Loading settings...'); // 添加日志
  return loadSettings();
});

app.whenReady().then(async () => {
  mainWindow = createWindow()
  
  // 等待窗口加载完成后再发送设置
  mainWindow.webContents.on('did-finish-load', () => {
    const settings = loadSettings()
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send('settings-updated', settings)
    }
  })
  
  // 开始定期收集性能数据
  startPerformanceCollection()
  
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      mainWindow = createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 获取进程列表
async function getProcessList() {
  try {
    const output = execSync('tasklist /FO CSV /NH', { encoding: 'utf8' })
    const processes = output.split('\n')
      .filter(line => line.trim())
      .map(line => {
        const [name, pid, sessionName, sessionNum, memUsage] = line.replace(/"/g, '').split(',')
        return {
          name,
          pid: parseInt(pid),
          memoryUsage: memUsage.trim()
        }
      })
      .sort((a, b) => parseInt(b.memoryUsage) - parseInt(a.memoryUsage))
      .slice(0, 10) // 只返回前10个内存占用最高的进程
    
    return processes
  } catch (error) {
    console.error('Error getting process list:', error)
    return []
  }
}

// 开始收集性能数据
function startPerformanceCollection() {
  // 初始化最后一次网络统计
  getNetworkTraffic()
  
  // 使用节流函数来限制更新频率
  let lastUpdate = 0
  const updateInterval = 2000 // 2秒更新一次
  
  setInterval(async () => {
    const now = Date.now()
    if (now - lastUpdate < updateInterval) return
    lastUpdate = now
    
    try {
      // 并行获取所有数据
      const [cpuUsage, processes] = await Promise.all([
        getCpuUsage(),
        getProcessList()
      ])
      
      const memUsage = getMemoryUsage()
      const networkTraffic = getNetworkTraffic()
      
      // 保存历史数据
      if (cpuUsage && cpuUsage.average) {
        performanceHistory.cpu.push({ 
          timestamp: now, 
          value: parseFloat(cpuUsage.average)
        })
        
        // 只保留最近10分钟的数据
        const tenMinutesAgo = now - 10 * 60 * 1000
        performanceHistory.cpu = performanceHistory.cpu.filter(item => item.timestamp > tenMinutesAgo)
      }
      
      if (memUsage && memUsage.usagePercent) {
        performanceHistory.memory.push({ 
          timestamp: now, 
          value: parseFloat(memUsage.usagePercent)
        })
        performanceHistory.memory = performanceHistory.memory.filter(item => item.timestamp > now - 10 * 60 * 1000)
      }
      
      if (networkTraffic) {
        performanceHistory.network.push({
          timestamp: now,
          rx: networkTraffic.rxSpeed,
          tx: networkTraffic.txSpeed
        })
        performanceHistory.network = performanceHistory.network.filter(item => item.timestamp > now - 10 * 60 * 1000)
      }
      
      // 发送更新到渲染进程
      if (mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.webContents.send('performance-update', {
          cpu: cpuUsage,
          memory: memUsage,
          network: networkTraffic,
          processes,
          history: performanceHistory
        })
      }
    } catch (error) {
      console.error('Error collecting performance data:', error)
    }
  }, 1000) // 检查间隔为1秒，但实际更新间隔为2秒
}

function getMemoryUsage() {
  const totalMem = os.totalmem()
  const freeMem = os.freemem()
  const usedMem = totalMem - freeMem
  return {
    total: formatBytes(totalMem),
    free: formatBytes(freeMem),
    used: formatBytes(usedMem),
    usagePercent: ((usedMem / totalMem) * 100).toFixed(1)
  }
}

// 获取磁盘信息
async function getDriveInfo() {
  if (process.platform === 'win32') {
    try {
      // 获取所有驱动器盘符
      const drives = execSync('wmic logicaldisk get caption', { encoding: 'utf8' })
        .trim()
        .split('\n')
        .slice(1)
        .map(drive => drive.trim())
        .filter(drive => drive)

      const driveInfo = []
      
      for (const drive of drives) {
        try {
          // 检查是否有权限访问该驱动器
          try {
            await fs.promises.access(`${drive}\\`, fs.constants.R_OK)
          } catch {
            // 如果没有访问权限,跳过该驱动器
            continue
          }

          const stats = fs.statSync(`${drive}\\`)
          const total = execSync(`wmic logicaldisk where "caption='${drive}'" get size`, { encoding: 'utf8' })
            .trim()
            .split('\n')[1]
            .trim()
          
          const free = execSync(`wmic logicaldisk where "caption='${drive}'" get freespace`, { encoding: 'utf8' })
            .trim()
            .split('\n')[1]
            .trim()
          
          const totalBytes = parseInt(total)
          const freeBytes = parseInt(free)
          const usedBytes = totalBytes - freeBytes
          
          driveInfo.push({
            name: drive,
            total: formatBytes(totalBytes),
            free: formatBytes(freeBytes),
            used: formatBytes(usedBytes),
            usagePercent: ((usedBytes / totalBytes) * 100).toFixed(1)
          })
        } catch (error) {
          console.error(`Error processing drive ${drive}:`, error)
          // 继续处理下一个驱动器
          continue
        }
      }
      
      return driveInfo
    } catch (error) {
      console.error('Error getting drive info:', error)
      return []
    }
  }
  return []
}

// 获取系统信息
ipcMain.handle('get-system-info', async () => {
  try {
    const cpus = os.cpus()
    const totalMem = os.totalmem()
    const freeMem = os.freemem()
    const usedMem = totalMem - freeMem
    const networkInterfaces = os.networkInterfaces()
    const gpuInfo = await getGPUInfo()
    const bootTime = await getBootTime()
    
    // 获取主网卡信息
    const mainInterface = Object.values(networkInterfaces)
      .flat()
      .find(ni => !ni.internal && ni.family === 'IPv4')

    // 获取磁盘信息
    const drives = await getDriveInfo()
    
    return {
      platform: os.platform(),
      arch: os.arch(),
      hostname: os.hostname(),
      release: os.release(),
      version: os.version(),
      cpus: {
        model: cpus[0].model,
        cores: cpus.length,
        speed: cpus[0].speed,
        details: cpus.map(cpu => ({
          speed: cpu.speed,
          times: cpu.times
        }))
      },
      gpu: gpuInfo,
      memory: {
        total: formatBytes(totalMem),
        free: formatBytes(freeMem),
        used: formatBytes(usedMem),
        usagePercent: ((usedMem / totalMem) * 100).toFixed(1)
      },
      network: mainInterface ? {
        address: mainInterface.address,
        netmask: mainInterface.netmask,
        mac: mainInterface.mac
      } : null,
      drives,
      bootTime: bootTime ? bootTime.toISOString() : null,
      uptime: formatUptime(os.uptime()),
      loadavg: os.loadavg(),
      userInfo: os.userInfo(),
      tempDir: os.tmpdir()
    }
  } catch (error) {
    console.error('Error getting system info:', error)
    return null
  }
})

// 获取系统负载
ipcMain.handle('get-system-load', async () => {
  try {
    const cpuUsage = await getCpuUsage()
    const memUsage = getMemoryUsage()
    const networkTraffic = getNetworkTraffic()
    const processes = await getProcessList()
    
    return {
      cpu: cpuUsage,
      memory: memUsage,
      network: networkTraffic,
      processes,
      history: performanceHistory
    }
  } catch (error) {
    console.error('Error getting system load:', error)
    return null
  }
})

// 导出系统信息
ipcMain.handle('export-system-info', async () => {
  try {
    const systemInfo = await ipcMain.handlers['get-system-info']()
    const systemLoad = await ipcMain.handlers['get-system-load']()
    
    const exportData = {
      timestamp: new Date().toISOString(),
      systemInfo,
      systemLoad,
      performanceHistory
    }
    
    const exportPath = path.join(app.getPath('downloads'), 'system-info.json')
    await fs.promises.writeFile(exportPath, JSON.stringify(exportData, null, 2))
    return { success: true, path: exportPath }
  } catch (error) {
    console.error('Error exporting system info:', error)
    return { success: false, error: error.message }
  }
})

// 处理获取目录内容的请求
ipcMain.handle('get-directories', async (event, dirPath) => {
  try {
    // 检查是否为系统保护目录
    const protectedDirs = ['C:\\Recovery', 'C:\\System Volume Information'];
    if (protectedDirs.includes(dirPath)) {
      return { error: 'ACCESS_DENIED' };
    }

    // 检查访问权限
    try {
      await fs.promises.access(dirPath, fs.constants.R_OK);
    } catch {
      return { error: 'ACCESS_DENIED' };
    }

    const items = await fs.promises.readdir(dirPath, { withFileTypes: true });
    const directories = [];
    
    for (const item of items) {
      if (item.isDirectory()) {
        const fullPath = path.join(dirPath, item.name);
        try {
          await fs.promises.access(fullPath, fs.constants.R_OK);
          directories.push({
            name: item.name,
            path: fullPath
          });
        } catch {
          // 跳过无权限访问的目录
          continue;
        }
      }
    }
    
    return { data: directories };
  } catch (error) {
    console.error('Error reading directory:', error);
    return { error: error.code || 'UNKNOWN_ERROR' };
  }
});

// 处理获取文件列表的请求
ipcMain.handle('get-files', async (event, dirPath) => {
  try {
    // 检查是否为系统保护目录
    const protectedDirs = ['C:\\Recovery', 'C:\\System Volume Information'];
    if (protectedDirs.includes(dirPath)) {
      return { error: 'ACCESS_DENIED' };
    }

    // 检查访问权限
    try {
      await fs.promises.access(dirPath, fs.constants.R_OK);
    } catch {
      return { error: 'ACCESS_DENIED' };
    }

    const items = await fs.promises.readdir(dirPath, { withFileTypes: true });
    const files = [];
    
    for (const item of items) {
      try {
        const fullPath = path.join(dirPath, item.name);
        try {
          await fs.promises.access(fullPath, fs.constants.R_OK);
        } catch {
          continue;
        }

        const stats = await fs.promises.stat(fullPath);
        files.push({
          name: item.name,
          path: fullPath,
          type: item.isDirectory() ? '文件夹' : '文件',
          size: item.isDirectory() ? '-' : formatBytes(stats.size),
          modifiedTime: new Date(stats.mtime).toLocaleString()
        });
      } catch (error) {
        console.error(`Error processing file ${item.name}:`, error);
        continue;
      }
    }
    
    return { data: files };
  } catch (error) {
    console.error('Error reading files:', error);
    return { error: error.code || 'UNKNOWN_ERROR' };
  }
});

async function checkAccess(dirPath) {
  try {
    await fs.promises.access(dirPath, fs.constants.R_OK)
    return true
  } catch {
    return false
  }
}

function formatSize(bytes) {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 修改人脸检测处理函数
async function detectFace(imagePath) {
  try {
    // 1. 读取并验证图片
    const imageBuffer = await fs.promises.readFile(imagePath)
    const image = sharp(imageBuffer)
    const metadata = await image.metadata()
    
    if (!metadata.width || !metadata.height) {
      throw new Error('无效的图片文件')
    }

    // 2. 计算人脸区域
    const aspectRatio = metadata.width / metadata.height
    let faceBox = {}

    if (aspectRatio > 1) {
      // 横向图片
      faceBox.height = Math.min(metadata.height, Math.floor(metadata.height * 0.9))
      faceBox.width = Math.min(metadata.width, Math.floor(faceBox.height * 0.75))
    } else {
      // 纵向图片
      faceBox.width = Math.min(metadata.width, Math.floor(metadata.width * 0.9))
      faceBox.height = Math.min(metadata.height, Math.floor(faceBox.width * 1.33))
    }

    // 居中定位
    faceBox.x = Math.max(0, Math.floor((metadata.width - faceBox.width) / 2))
    faceBox.y = Math.max(0, Math.floor((metadata.height - faceBox.height) * 0.3))

    // 3. 提取并处理人脸区域
    const processedFace = await sharp(imageBuffer)
      .extract({
        left: faceBox.x,
        top: faceBox.y,
        width: faceBox.width,
        height: faceBox.height
      })
      .modulate({
        brightness: 1.05,
        saturation: 1.1
      })
      .sharpen({
        sigma: 1.2,
        m1: 0.8,
        m2: 0.7
      })
      .toBuffer()

    return {
      success: true,
      face: processedFace.toString('base64'),
      box: faceBox,
      dimensions: {
        originalWidth: metadata.width,
        originalHeight: metadata.height,
        faceWidth: faceBox.width,
        faceHeight: faceBox.height
      }
    }
  } catch (error) {
    console.error('人脸检测和抠图失败:', error)
    return {
      success: false,
      error: error.message || '处理失败'
    }
  }
}

// 注册 IPC 处理函数
ipcMain.handle('detect-face', async (event, imagePath) => {
  return await detectFace(imagePath)
})

// 优化证件照处理函数
ipcMain.handle('process-id-photo', async (event, params) => {
  try {
    const {
      portraitUrl,
      size,
      background,
      position,
      options
    } = params
    
    // 处理图片数据
    let imageBuffer
    if (portraitUrl.startsWith('data:image')) {
      // 处理 base64 数据
      imageBuffer = Buffer.from(portraitUrl.split(',')[1], 'base64')
    } else {
      // 处理文件路径
      const imagePath = portraitUrl.replace('file://', '')
      imageBuffer = await fs.promises.readFile(imagePath)
    }
    
    let image = sharp(imageBuffer)
    
    // 获取图片元数据
    const metadata = await image.metadata()
    
    // 调整大小和位置
    const photoSize = PHOTO_SIZES[size]
    const targetWidth = Math.round(photoSize.width * (position.scale / 100))
    const targetHeight = Math.round(photoSize.height * (position.scale / 100))
    
    // 计算缩放比例
    const scale = Math.min(
      targetWidth / metadata.width,
      targetHeight / metadata.height
    )
    
    // 应用图像处理
    image = image
      .resize({
        width: Math.round(metadata.width * scale),
        height: Math.round(metadata.height * scale),
        fit: 'contain',
        position: 'center'
      })
    
    // 应用美化选项
    if (options.includes('whitening')) {
      image = image
        .modulate({
          brightness: 1.1,
          saturation: 0.9,
          hue: 5
        })
        .gamma(0.9)
    }
    
    if (options.includes('removeWrinkle')) {
      image = image
        .blur(0.5)
        .sharpen({
          sigma: 1,
          m1: 0.1,
          m2: 0.2
        })
    }
    
    if (options.includes('removeAcne')) {
      image = image
        .median(2)
        .sharpen({
          sigma: 0.8,
          m1: 0.2,
          m2: 0.3
        })
    }
    
    if (options.includes('faceLift')) {
      // 通过调整宽度实现简单的瘦脸效果
      image = image.resize({
        width: Math.round(metadata.width * 0.95),
        height: metadata.height,
        fit: 'contain',
        position: 'center'
      })
    }

    // 调整图片大小以适应证件照尺寸
    image = image.resize({
      width: photoSize.width,
      height: photoSize.height,
      fit: 'contain',
      position: 'center',
      background: { r: 0, g: 0, b: 0, alpha: 0 }
    })
    
    // 创建背景
    const bgColor = {
      white: { r: 255, g: 255, b: 255, alpha: 1 },
      blue: { r: 67, g: 142, b: 219, alpha: 1 },
      red: { r: 190, g: 42, b: 65, alpha: 1 }
    }[background] || { r: 255, g: 255, b: 255, alpha: 1 }
    
    // 创建背景画布
    const canvas = await sharp({
      create: {
        width: photoSize.width,
        height: photoSize.height,
        channels: 4,
        background: bgColor
      }
    })
    .jpeg()
    .toBuffer()
    
    // 获取处理后的图片buffer
    const processedImage = await image
      .jpeg()
      .toBuffer()
    
    // 合成最终图片
    const composite = await sharp(canvas)
      .composite([{
        input: processedImage,
        gravity: 'center',
        blend: 'over'
      }])
      .jpeg({
        quality: 95,
        chromaSubsampling: '4:4:4'
      })
      .toBuffer()
    
    // 保存临时文件
    const tempPath = path.join(app.getPath('temp'), `processed_${Date.now()}.jpg`)
    await fs.promises.writeFile(tempPath, composite)
    
    return {
      success: true,
      processedUrl: `file://${tempPath}`,
      size: photoSize
    }
  } catch (error) {
    console.error('证件照处理失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
})

// 保存处理后的图片
ipcMain.handle('save-processed-image', async (event, imageData, filename) => {
  try {
    const { filePath } = await dialog.showSaveDialog({
      defaultPath: filename,
      filters: [
        { name: 'Images', extensions: ['jpg', 'jpeg', 'png'] }
      ]
    })
    
    if (filePath) {
      const imageBuffer = Buffer.from(imageData.replace(/^data:image\/\w+;base64,/, ''), 'base64')
      await fs.promises.writeFile(filePath, imageBuffer)
      return { success: true, filePath }
    }
  } catch (error) {
    console.error('Save image failed:', error)
    throw error
  }
})

// 获取支持的证件照尺寸
ipcMain.handle('get-photo-sizes', () => {
  return PHOTO_SIZES
})

// 优化导出打印文件功能
ipcMain.handle('export-print-file', async (event, params) => {
  try {
    const {
      processedUrl,
      rows,
      cols,
      size,
      spacing = 0
    } = params
    
    // 读取处理后的图片
    const imagePath = processedUrl.replace('file://', '')
    const image = sharp(imagePath)
    const imageBuffer = await image.toBuffer()
    
    // 获取照片尺寸
    const photoSize = PHOTO_SIZES[size]
    
    // 计算打印布局尺寸（考虑间距）
    const printWidth = photoSize.width * cols + spacing * (cols - 1)
    const printHeight = photoSize.height * rows + spacing * (rows - 1)
    
    // 创建空白画布
    const canvas = sharp({
      create: {
        width: printWidth,
        height: printHeight,
        channels: 4,
        background: { r: 255, g: 255, b: 255, alpha: 1 }
      }
    })
    
    // 生成图片阵列
    const composites = []
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
        composites.push({
          input: imageBuffer,
          left: j * (photoSize.width + spacing),
          top: i * (photoSize.height + spacing)
        })
      }
    }
    
    // 合成打印文件
    const result = await canvas
      .composite(composites)
      .jpeg({
        quality: 95,
        chromaSubsampling: '4:4:4'
      })
      .toBuffer()
    
    // 弹出保存对话框
    const { filePath } = await dialog.showSaveDialog({
      title: '保存打印文件',
      defaultPath: `证件照打印_${size}_${rows}x${cols}_${Date.now()}.jpg`,
      filters: [
        { name: '图片文件', extensions: ['jpg', 'jpeg'] }
      ]
    })
    
    if (filePath) {
      await fs.promises.writeFile(filePath, result)
      return { 
        success: true, 
        filePath,
        dimensions: {
          width: printWidth,
          height: printHeight
        }
      }
    } else {
      return {
        success: false,
        error: '用户取消保存'
      }
    }
  } catch (error) {
    console.error('导出打印文件失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
})

// 处理保存对话框
ipcMain.handle('save-dialog', async (event, options) => {
  return await dialog.showSaveDialog(options)
}) 